<?php

class area_model extends CI_Model
{
	public $table_name='area';
	public $offset=0.01;//never larger than 0.5, 0.2 is too long, depends on the lat and longi
	function __construct()
	{
		parent::__construct();
		
		$config['hostname'] = 'localhost';
		$config['username'] = 'root';
		$config['password'] = '';
		$config['database'] = 'helloworld';
		$config['dbdriver'] = 'mysql';
		$config['dbprefix'] = '';
		$config['pconnect'] = TRUE;
		$config['db_debug'] = TRUE;
		$config['cache_on'] = FALSE;
		$config['cachedir'] = '';
		$config['char_set'] = 'utf8';
		$config['dbcollat'] = 'utf8_general_ci';
		$config['swap_pre'] = '';
		$config['autoinit'] = TRUE;
		$config['stricton'] = FALSE;
		//@@@@@@testers: check the database name before start!!
		$this->load->database($config);
	}
	function get_near($lat, $longi)
	{
		
		$latlow = (string)( (double)($lat)-$this->offset );
		$lathigh = (string)( (double)($lat)+$this->offset );
		$longilow = (string)( (double)($longi)-$this->offset );
		$longihigh = (string)( (double)($longi)+$this->offset );
		
		return $this->db->query('
				select areaid, areaname,lat, longi
				from area
				where lat > '.$latlow.' and lat <'.$lathigh.' and
					  longi > '.$longilow.' and longi <'.$longihigh.'
			');

	}
	function getAll()
	{
		return $this->db->get($this->table_name);
	}	
	
	//full functionality, @@required field name to be matched@@
	function create()
	{
		
		$new_area['areaname'] = $this->input->post('areaname');
		$new_area['lat'] =$this->input->post('lat');
		$new_area['longi'] = $this->input->post('longi');
		$new_area['contributorid']=$this->session->userdata('userid');
	
		$this->db->insert($this->table_name, $new_area);
		
		$q=$this->db->query('
				select areaid,areaname
				from area
				where lat ='.$new_area['lat'].' and longi ='.$new_area['longi'].'
				');
		$a=$this-> ChangeQueryResultToArray($q);
		return $a[0];

	}
	
	//not yet being used
	function update($area)
	{
		$this->db->where('area', $profile['areaid']);
		$this->db->update($this->table_name, $area);
	}
	
	
	// not yet being used
	function get_area($area)
	{
		reset($area);

		while (list($field, $content) = each($area))
		{
			$this->db->where($field, $content);
		}
		return $this->db->get($this->table_name);
		
	}
	
	function ChangeQueryResultToArray($query)
	{
		if($query->num_rows() > 0)
		{
			foreach ($query->result() as $row)
			{
				$data[] = $row;
			}
			return $data;
		}
	}
	

}
?>
